<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Fetch Input Search</title>
  <style>
    body {
      font-family: Arial, sans-serif;
    }
    #result {
      margin-top: 20px;
    }
  </style>
</head>
<body>
  <h1>Search Example</h1>
  <input type="text" id="searchInput" placeholder="Type to search...">
  <div id="result"></div>

  <script>
    let controller;

    document.getElementById('searchInput').addEventListener('input', (event) => {
      // 取消控制器
      const query = event.target.value;

      if (controller) {
        controller.abort();
      }

      controller = new AbortController();
      const signal = controller.signal;

      fetch(`https://jsonplaceholder.typicode.com/posts?title_like=${query}`, { signal })
        .then(response => response.json())
        .then(data => {
          displayResults(data);
        })
        .catch(error => {
          if (error.name === 'AbortError') {
            console.log('Fetch aborted');
          } else {
            console.error(error);
          }
        });
    });

    function displayResults(data) {
      const resultDiv = document.getElementById('result');
      resultDiv.innerHTML = '';

      if (data.length === 0) {
        resultDiv.textContent = 'No results found';
      } else {
        data.forEach(item => {
          const div = document.createElement('div');
          div.textContent = item.title;
          resultDiv.appendChild(div);
        });
      }
    }
  </script>
</body>
</html>
